#include <stdio.h>
#include <omp.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include "buzzlock.h"

#define THREADCOUNT 100
#define GOLD 30
#define BLACK THREADCOUNT-GOLD
#define THREADPOOL 1   

#define TIMEOUT 10  // in us
#define ACTIVITY 5 // in us
bzz_t GTLOCK;

void thread(){
    struct timeval t1,t2;
    struct timespec t5,t6;
    double elapsedTime, elapsedTime2, test, test2;
    int ID = omp_get_thread_num();
    
    
    if(ID % 5) bzz_color(BZZ_BLACK, GTLOCK);
    else bzz_color(BZZ_GOLD, GTLOCK);
    
    gettimeofday(&t1,NULL);
    clock_gettime(CLOCK_REALTIME, &t5);
    bzz_lock(GTLOCK);
    gettimeofday(&t2,NULL);
    clock_gettime(CLOCK_REALTIME, &t6);
    
    usleep(ACTIVITY); // ACTIVITY

    bzz_release(GTLOCK);

    
    elapsedTime = (t2.tv_sec - t1.tv_sec);      // sec 
    test = (t2.tv_usec - t1.tv_usec)/1000000;      // usec 
    //elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000000.0;   //  us
    
    elapsedTime2 = (t6.tv_sec - t5.tv_sec);      // sec 
    test2 = (t6.tv_nsec - t5.tv_nsec)/1000000000.0;      // usec 
    //elapsedTime2 += (t6.tv_nsec - t5.tv_nsec) / 1000000000.0;   //  us

    
    if(ID % 5){ 
          //printf("%d wait BLACK = %f\n",ID, elapsedTime2);
          //printf("%d wait BLACK = %f\n",ID, test2);
          printf("%d wait BLACK %us %uns  \n", ID, t6.tv_sec-t5.tv_sec, t6.tv_nsec - t5.tv_nsec);
          //printf("%d wait BLACK = %f\n",ID, elapsedTime);
          //printf("%d wait BLACK = %f\n",ID, test);
          //printf("%d wait BLACK %us %uus \n",ID, t2.tv_sec - t1.tv_sec,t2.tv_usec - t1.tv_usec); 
          //printf("%us%uns  \n", t6.tv_sec-t5.tv_sec, t6.tv_nsec - t5.tv_nsec);
          //printf("BLACK\n");
    }
    else{
          //printf("%d wait GOLD = %f\n",ID, elapsedTime2);
          //printf("%d wait GOLD = %f\n",ID, test2);
          printf("%d wait GOLD %us %uns \n", ID, t6.tv_sec-t5.tv_sec, t6.tv_nsec - t5.tv_nsec);
          //printf("%d wait GOLD = %f\n",ID, elapsedTime);
          //printf("%d wait GOLD = %f\n",ID, test);
          //printf("%d wait GOLD %us %uus \n",ID, t2.tv_sec - t1.tv_sec,t2.tv_usec - t1.tv_usec); 
          //printf("%us%uns \n", t6.tv_sec-t5.tv_sec, t6.tv_nsec - t5.tv_nsec);
          //printf("GOLD\n"); 
    }
	
}


int main(){
    
    omp_set_num_threads(THREADCOUNT);
    init_bzz(&GTLOCK,THREADPOOL,TIMEOUT); 
    
    
#pragma omp parallel num_threads(100)
    {
        
        thread();
        
    }
    
    bzz_kill(GTLOCK);
    
}


